package org.snail.common;

import lombok.extern.log4j.Log4j;
import org.snail.constant.ErrCodeConstant;
import org.snail.exception.CommonException;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Log4j
public class FileUtils {
    /**
     * 上传文件到指定服务器
     * @param file
     * @param pathHome
     * @return
     */
    public static File transferToServer (CommonsMultipartFile file, String pathHome) {
        File serverFile = null;
        try {
            log.info("fileName：" + file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            String[] fileStr = fileName.split("\\.");
            if(fileStr.length==0){
                log.error("上传文件，没有文件名");
                throw  new CommonException(ErrCodeConstant.FILE_NOT_FOUND,"上传文件，没有文件名");
            }
            String fileType = fileStr[fileStr.length-1];
            String  path = pathHome + "/" +fileStr[0]+ new Date().getTime() + "."+fileType;
            serverFile = new File(path);
            if (!serverFile.exists()) {
                serverFile.mkdirs();
            }
            //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
            file.transferTo(serverFile);
        }catch (FileNotFoundException e){
            log.error("找不到文件！", e);
        }catch (IOException e){
            log.error(e);
        } catch (CommonException e) {
            log.error(e);
        }
        return  serverFile;
    }

    public static File[]  listFiles(String pathHome){
        File file = new File(pathHome);
        File[] tempList = file.listFiles();
        return tempList;
    }
}